﻿using System.Web;
using System.Xml;


namespace Mangox.Common
{
    /// <summary>
    ///  读写XML类
    ///  适合各种config 以及自定义配置
    /// </summary>
    public static class XmlConfigHelper
    {
        //D:\work\prj\VP-VPlatform\XmlAndXsd\bin\Release\
        public static string serverPath = System.AppDomain.CurrentDomain.BaseDirectory;
        public static string configPath = "config.xml";
        /// <summary>
        /// 保存XML
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SetConfig(string key, string value)
        {
            XmlDocument doc = new XmlDocument();
            //获得配置文件的全路径
            string strFileName = HttpContext.Current.Server.MapPath(configPath); // System.AppDomain.CurrentDomain.BaseDirectory + "\\DLTiClient.exe.config";

            //加载Xml
            doc.Load(strFileName);

            //找出名称为“appSettings”的所有元素
            XmlNodeList nodes = doc.GetElementsByTagName("appSettings");

            for (int i = 0; i < nodes[0].ChildNodes.Count; i++)
            {
                var node = nodes[0].ChildNodes[i];
                if (node.Attributes["key"].Value.ToString().Equals(key))
                {
                    node.Attributes["value"].Value = value;
                }
            }
            //保存上面的修改
            doc.Save(strFileName);
            return true;
        }

        /// <summary>
        /// 读取XML
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetConfig(string key)
        {
            XmlDocument doc = new XmlDocument();
            //获得配置文件的全路径
            // System.AppDomain.CurrentDomain.BaseDirectory + "\\DLTiClient.exe.config";
            string strFileName = HttpContext.Current.Server.MapPath(configPath);
            //加载Xml
            doc.Load(strFileName);
            //找出名称为“appSettings”的所有元素
            XmlNodeList nodes = doc.GetElementsByTagName("appSettings");

            for (int i = 0; i < nodes[0].ChildNodes.Count; i++)
            {
                var node = nodes[0].ChildNodes[i];
                if (node.Attributes["key"].Value.ToString().Equals(key))
                {
                    return node.Attributes["value"].Value;
                }
            }
            return string.Empty;
        }
    }
}